<?php

namespace App\Kuafu\Mybank\Service;

use App\Exceptions\BaseException;
use App\Kuafu\Base\Service\BaseService;
use App\Kuafu\Mybank\Model\MybankBatchNoRecordModel;
use App\Kuafu\Mybank\Model\MybankBillRecordBindModel;
use App\Kuafu\Mybank\Model\MybankBillRecordModel;
use App\Kuafu\Mybank\Model\MybankEntryModel;
use App\Kuafu\Mybank\Model\MybankFuyouBillRecordModel;
use App\Kuafu\Mybank\Model\MybankOrderRecordModel;
use App\Kuafu\Mybank\Model\MybankShopBindModel;
use App\Kuafu\Mybank\Model\MybankVostroBillModel;
use App\Kuafu\Mybank\Model\MybankWalletRecordModel;
use App\Kuafu\Mybank\Resources\MybankEntryDetailResource;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\Order\Model\OrderSplitModel;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\Shop\Resources\B\ShopSimpleResource;
use App\Kuafu\WaiMai\Enum\WaiMaiDBEnum;
use App\Kuafu\WaiMai\Model\WaiMaiOrderModel;
use App\Library\FeiShu\SendFs;
use App\Remote\Mybank\MybankAccountRemote;
use App\Remote\Mybank\MybankCreateBatchRemote;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Symfony\Component\HttpFoundation\Response as ResponseAlias;

class MybankBatchService extends BaseService
{

    /**
     * 处理历史账单
     *
     * @param array $data
     * @return array
     */
    public static function dealBatchMinusAmount(array $data): array
    {
        $dataCollect = collect($data);

        $matchAmountData = $dataCollect->where('transAmount', '<', 0);

        if ($matchAmountData->count()) {
            // 存在负数
            $orderRecordModel = new MybankOrderRecordModel();
            // 匹配到负数金额
            $totalAmount = 0;
            foreach ($matchAmountData as $item) {
                // 生成对应代负账单
                $absAmount = abs($item['transAmount']);
                $type      = MybankOrderService::switchBillRecordSource($item['source']);
                $orderRecordModel->genBillOrder(
                    $item['shopId'],
                    $item['merchantId'],
                    MybankOrderRecordModel::TYPE_TEXT[$type] . ':' . $absAmount / 100 . '元',
                    $absAmount,
                    $item['transId'],
                    MybankOrderRecordModel::TYPE_TEXT[$type],
                    $type
                );
                $totalAmount = bcadd($totalAmount, $absAmount);
            }

            $list = $dataCollect->where('transAmount', '>', 0)->values()->toArray();
        } else {
            // 不存在负数

            // 查询是否存在历史账单
            $historyList = MybankOrderRecordModel::query()
                                                 ->where('type', [
                                                     MybankOrderRecordModel::TYPE_BILL_TYPE_ELE,
                                                     MybankOrderRecordModel::TYPE_BILL_TYPE_MT,
                                                 ])
                                                 ->where('payStatus', '!=', MybankOrderRecordModel::PAY_STATUS_PAID)
                                                 ->get();
            // 判断是否相同的类型账单
            if ($historyList->count()) {
                $merchantIdList    = $historyList->pluck('merchantId')->toArray();
                $merchantIdKeyList = $historyList->keyBy('merchantId')->toArray();

                $dataCollect = $dataCollect->toArray();
                foreach ($dataCollect as &$item) {
                    $type = MybankOrderService::switchBillRecordSource($item['source']);
                    if (in_array($item['merchantId'], $merchantIdList) &&
                        $merchantIdKeyList[$item['merchantId']]['type'] == $type) {
                        $info = $merchantIdKeyList[$item['merchantId']];

                        if (bccomp($item['transAmount'], $info['brokerage']) > 0) {
                            $item['transAmount'] = (int)bcsub($item['transAmount'], $info['brokerage']);

                            MybankOrderRecordModel::query()
                                                  ->where('orderId', $info['orderId'])
                                                  ->update([
                                                      'completeAt'    => time(),
                                                      'paidBrokerage' => $info['brokerage'],
                                                      'payStatus'     => MybankOrderRecordModel::PAY_STATUS_PAID,
                                                  ]);
                        }
                    }
                }

                $totalAmount = 0;
                $list        = $dataCollect;
            } else {
                $totalAmount = 0;
                $list        = $data;
            }
        }

        return [$totalAmount, $list];
    }
}
